<template>
    <div class="users-container">
      <div class="header">
        <div class="left">
          <h2>用户管理</h2>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>添加用户
          </el-button>
        </div>
        <div class="right">
          <el-input
            v-model="searchQuery"
            placeholder="搜索用户名/姓名/邮箱"
            class="search-input"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
  
      <el-card class="table-card">
        <el-table
          v-loading="loading"
          :data="users"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="role" label="角色" width="100">
            <template #default="{ row }">
              <el-tag :type="getRoleType(row.role)">{{ getRoleLabel(row.role) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="department" label="部门/院系" width="150" />
          <el-table-column prop="studentId" label="学号/工号" width="120" />
          <el-table-column prop="email" label="邮箱" min-width="180" />
          <el-table-column prop="phone" label="电话" width="120" />
          <el-table-column prop="createTime" label="注册时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="{ row }">
              <el-button-group>
                <el-button
                  v-if="row.status === 'PENDING'"
                  type="success"
                  size="small"
                  @click="handleApprove(row)"
                >
                  通过
                </el-button>
                <el-button
                  v-if="row.status === 'PENDING'"
                  type="danger"
                  size="small"
                  @click="handleReject(row)"
                >
                  拒绝
                </el-button>
                <el-button
                  v-if="row.status === 'APPROVED'"
                  type="warning"
                  size="small"
                  @click="handleDisable(row)"
                >
                  禁用
                </el-button>
                <el-button
                  v-if="row.status === 'DISABLED'"
                  type="success"
                  size="small"
                  @click="handleEnable(row)"
                >
                  启用
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  @click="handleEdit(row)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDelete(row)"
                >
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
  
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
  
      <!-- 用户表单对话框 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
      >
        <el-form
          ref="userFormRef"
          :model="userForm"
          :rules="userRules"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" :disabled="!!userForm.id" />
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="!userForm.id">
            <el-input v-model="userForm.password" type="password" show-password />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="userForm.name" />
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="userForm.role" class="w-full">
              <el-option label="管理员" value="ADMIN" />
              <el-option label="教师" value="TEACHER" />
              <el-option label="学生" value="STUDENT" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门/院系" prop="department">
            <el-input v-model="userForm.department" />
          </el-form-item>
          <el-form-item label="学号/工号" prop="studentId">
            <el-input v-model="userForm.studentId" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="userForm.phone" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  export default {
    name: 'AdminUsersPage'
  }
  </script>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { 
    getUsers, 
    approveUser, 
    rejectUser, 
    disableUser, 
    enableUser, 
    createUser, 
    updateUser, 
    deleteUser 
  } from '@/api/admin/user'
  import { formatDate } from '@/utils/format'
  
  // 表格数据
  const users = ref([])
  const loading = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  
  // 搜索相关
  const searchQuery = ref('')
  const handleSearch = () => {
    currentPage.value = 1
    fetchUsers()
  }
  
  // 表单相关
  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const userFormRef = ref(null)
  const submitting = ref(false)
  
  const userForm = ref({
    username: '',
    password: '',
    name: '',
    role: '',
    department: '',
    studentId: '',
    email: '',
    phone: ''
  })
  
  const userRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    name: [
      { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    role: [
      { required: true, message: '请选择角色', trigger: 'change' }
    ],
    email: [
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    phone: [
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ]
  }
  
  // 获取用户列表
  const fetchUsers = async () => {
    try {
      loading.value = true
      const params = {
        page: currentPage.value - 1,
        size: pageSize.value,
        query: searchQuery.value
      }
      const response = await getUsers(params)
      users.value = response.content
      total.value = response.totalElements
    } catch (error) {
      console.error('Failed to fetch users:', error)
      ElMessage.error('获取用户列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 角色标签配置
  const getRoleLabel = (role) => {
    const labels = {
      'ADMIN': '管理员',
      'TEACHER': '教师',
      'STUDENT': '学生'
    }
    return labels[role] || role
  }
  
  const getRoleType = (role) => {
    const types = {
      'ADMIN': 'danger',
      'TEACHER': 'warning',
      'STUDENT': 'info'
    }
    return types[role] || ''
  }
  
  // 状态标签配置
  const getStatusLabel = (status) => {
    const labels = {
      'PENDING': '待审核',
      'APPROVED': '已通过',
      'REJECTED': '已拒绝',
      'DISABLED': '已禁用'
    }
    return labels[status] || status
  }
  
  const getStatusType = (status) => {
    const types = {
      'PENDING': 'warning',
      'APPROVED': 'success',
      'REJECTED': 'danger',
      'DISABLED': 'info'
    }
    return types[status] || ''
  }
  
  // 添加用户
  const handleAdd = () => {
    dialogTitle.value = '添加用户'
    userForm.value = {
      username: '',
      password: '',
      name: '',
      role: '',
      department: '',
      studentId: '',
      email: '',
      phone: ''
    }
    dialogVisible.value = true
  }
  
  // 编辑用户
  const handleEdit = (row) => {
    dialogTitle.value = '编辑用户'
    userForm.value = { ...row }
    dialogVisible.value = true
  }
  
  // 删除用户
  const handleDelete = async (row) => {
    try {
      await ElMessageBox.confirm(
        `确定要删除用户 ${row.name || row.username} 吗？`, 
        '警告', 
        {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }
      )
      
      loading.value = true
      await deleteUser(row.id)
      
      // 验证删除是否成功
      try {
        const checkUser = await getUsers({ 
          page: 0, 
          size: 1, 
          query: row.username 
        })
        if (checkUser.content.length > 0 && checkUser.content[0].id === row.id) {
          throw new Error('删除失败，用户仍然存在')
        }
      } catch (error) {
        console.error('Failed to verify deletion:', error)
      }
      
      ElMessage.success('删除成功')
      await fetchUsers() // 重新加载用户列表
      
    } catch (error) {
      if (error !== 'cancel') {
        console.error('Failed to delete user:', error)
        ElMessage.error(error.message || '删除失败')
      }
    } finally {
      loading.value = false
    }
  }
  
  // 提交表单
  const handleSubmit = async () => {
    if (!userFormRef.value) return
    
    try {
      await userFormRef.value.validate()
      submitting.value = true
      
      if (userForm.value.id) {
        await updateUser(userForm.value.id, userForm.value)
        ElMessage.success('更新成功')
      } else {
        await createUser(userForm.value)
        ElMessage.success('添加成功')
      }
      
      dialogVisible.value = false
      fetchUsers()
    } catch (error) {
      console.error('Form submission failed:', error)
      ElMessage.error('提交失败')
    } finally {
      submitting.value = false
    }
  }
  
  // 处理用户审批
  const handleApprove = async (row) => {
    try {
      await ElMessageBox.confirm(`确定通过用户 ${row.name} 的注册申请吗？`)
      await approveUser(row.id)
      ElMessage.success('已通过用户注册申请')
      fetchUsers()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('Failed to approve user:', error)
        ElMessage.error('操作失败')
      }
    }
  }
  
  const handleReject = async (row) => {
    try {
      await ElMessageBox.confirm(`确定拒绝用户 ${row.name} 的注册申请吗？`)
      await rejectUser(row.id)
      ElMessage.success('已拒绝用户注册申请')
      fetchUsers()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('Failed to reject user:', error)
        ElMessage.error('操作失败')
      }
    }
  }
  
  const handleDisable = async (row) => {
    try {
      await ElMessageBox.confirm(`确定禁用用户 ${row.name} 吗？`)
      await disableUser(row.id)
      ElMessage.success('已禁用用户')
      fetchUsers()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('Failed to disable user:', error)
        ElMessage.error('操作失败')
      }
    }
  }
  
  // 处理启用用户
  const handleEnable = async (row) => {
    try {
      await ElMessageBox.confirm(`确定要启用用户 ${row.name} 吗？`)
      await enableUser(row.id)
      ElMessage.success('已启用用户')
      fetchUsers()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('Failed to enable user:', error)
        ElMessage.error('操作失败')
      }
    }
  }
  
  // 分页处理
  const handleSizeChange = (val) => {
    pageSize.value = val
    fetchUsers()
  }
  
  const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchUsers()
  }
  
  // 在组件挂载时获取用户列表
  onMounted(() => {
    fetchUsers()
  })
  </script>
  
  <style scoped>
  .users-container {
    padding: 20px;
  }
  
  .header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .left {
    display: flex;
    align-items: center;
    gap: 16px;
  }
  
  .search-input {
    width: 300px;
  }
  
  .table-card {
    margin-bottom: 20px;
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  :deep(.el-button-group) {
    .el-button {
      padding: 5px 12px;
    }
  }
  
  .w-full {
    width: 100%;
  }
  </style>